package com.jinzhi.jzweb.controller.modelConfig;


import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.itextpdf.text.pdf.PdfReader;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzweb.domain.modelConfig.DeclareDO;
import com.jinzhi.jzweb.domain.modelConfig.DeclareFileDO;
import com.jinzhi.jzweb.domain.modelConfig.DeclareTypeDO;
import com.jinzhi.jzweb.service.modelConfig.DeclareFileService;
import com.jinzhi.jzweb.service.modelConfig.DeclareService;
import com.jinzhi.jzweb.service.modelConfig.DeclareTypeService;
import com.jinzhi.oss.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.http.entity.ContentType;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.instrument.classloading.SimpleLoadTimeWeaver;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.ui.Model;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.Result;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;

/**
 * 
 * <pre>
 * 申报类型表
 * </pre>
 * <small> 2024-01-10 09:25:22 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/declareType")
@Api(value = "申报类型信息",tags = "申报类型信息")
public class DeclareTypeController extends BaseController {

	private final DeclareTypeService declareTypeService;

	private final DeclareService declareService;

	private final DeclareFileService declareFileService;

	public DeclareTypeController(DeclareTypeService declareTypeService,DeclareService declareService,DeclareFileService declareFileService) {
		this.declareTypeService = declareTypeService;
		this.declareService = declareService;
		this.declareFileService = declareFileService;

	}

	@ApiOperation(value = "后台申报列表祥请入口", notes = "申报列表祥请入口")
	@GetMapping()
	@RequiresPermissions("jzweb:declareType:declareType")
	String DeclareType(){
	    return "jzweb/declareType/declareType";
	}

	@ApiOperation(value = "后台申报列表祥请接口", notes = "申报列表祥请接口")
	@ResponseBody
	@GetMapping("/list")
	public Result<Page<DeclareTypeDO>> list(DeclareTypeDO declareTypeDO){
		// 查询列表数据
		Page<DeclareTypeDO> page = new Page<>(declareTypeDO.getCurrent(),declareTypeDO.getSize());
		EntityWrapper<DeclareTypeDO> wrapper = new EntityWrapper<>();
		if(!Objects.isNull(declareTypeDO.getDeclareId())){
			wrapper.eq("declare_id",declareTypeDO.getDeclareId());
		}
		Page<DeclareTypeDO> pageList = declareTypeService.selectPage(page, wrapper);
		for (DeclareTypeDO record : pageList.getRecords()) {
			EntityWrapper<DeclareFileDO> fileWrapper = new EntityWrapper<>();
			fileWrapper.eq("declare_type_id",record.getId());
			List<DeclareFileDO> declareFileDOS = declareFileService.selectList(fileWrapper);
			record.setDeclareFileDOS(declareFileDOS);
		}
		return Result.ok(pageList);
    }


	@ApiOperation(value = "后台审核接口", notes = "后台审核接口")
	@Log("后台审核接口")
	@ResponseBody
	@PostMapping("/process")
	@RequiresPermissions("jzweb:declareType:process")
	public Result<String>  process(DeclareDO declareDTO){
		DeclareDO declareDO = declareService.selectById(declareDTO.getDeclareId());
		declareDO.setStatus(declareDTO.getStatus());
		if(StringUtil.isNotNull(declareDTO.getRemark())){
			declareDO.setRemark(declareDTO.getRemark());
		}
		boolean update = declareService.updateById(declareDO);
		return update ? Result.ok() : Result.fail();
	}
	
	@GetMapping("/add")
	@RequiresPermissions("jzweb:declareType:add")
	String add(){
	    return "jzweb/declareType/add";
	}

	@GetMapping("/edit/{id}")
	@RequiresPermissions("jzweb:declareType:edit")
	String edit(@PathVariable("id") Long id,Model model){
		DeclareTypeDO declareType = declareTypeService.selectById(id);
		model.addAttribute("declareType", declareType);
	    return "jzweb/declareType/edit";
	}
	
	@Log("添加申报类型表")
	@ResponseBody
	@PostMapping("/save")
	@RequiresPermissions("jzweb:declareType:add")
	public Result<String> save( DeclareTypeDO declareType){
		declareTypeService.insert(declareType);
        return Result.ok();
	}
	
	@Log("修改申报类型表")
	@ResponseBody
	@RequestMapping("/update")
	@RequiresPermissions("jzweb:declareType:edit")
	public Result<String>  update( DeclareTypeDO declareType){
		boolean update = declareTypeService.updateById(declareType);
		return update ? Result.ok() : Result.fail();
	}
	
	@Log("删除申报类型表")
	@PostMapping( "/remove")
	@ResponseBody
	@RequiresPermissions("jzweb:declareType:remove")
	public Result<String>  remove( Long id){
		declareTypeService.deleteById(id);
        return Result.ok();
	}
	
	@Log("批量删除申报类型表")
	@PostMapping( "/batchRemove")
	@ResponseBody
	@RequiresPermissions("jzweb:declareType:batchRemove")
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		declareTypeService.deleteBatchIds(Arrays.asList(ids));
		return Result.ok();
	}

	@Autowired
	private DocumentConverter converter;  //用于转换

	@Autowired
	private OssService ossService;
	/**
	 *
	 * @param fileurl 文件url
	 * @return
	 */
	public Map fileUrlToPdf(String fileurl) throws Exception {

		Map mymap = new HashMap();
		String uploadPdfUrl = "";

		String[] str = fileurl.split("/");
		String newfileName = str[str.length - 1];
		//去掉后缀
		String[] str2 = newfileName.split("\\.");
		String newfileName2 = str2[0];
		System.out.println("newfileNameUrl:" + newfileName2);

		String savePath = File.separator+"data"+File.separator+"jinzhiFile"; //pdf文件生成保存的路径

		String fileName = newfileName2;
		String fileType = ".pdf"; //pdf文件后缀
		String newFileMix = savePath + File.separator+fileName + fileType;
		int pagecount = 0;

		//转换
		File downloadFile = null;
		boolean flag = false;
		//中文转换一下
		fileurl=fileurl.replace(newfileName2, URLEncoder.encode(newfileName2, "UTF-8")) ;
		// 构造URL
		URL weburl = new URL(fileurl);
		// 打开连接
		URLConnection con = weburl.openConnection();
		// 设置请求超时为5s
		con.setConnectTimeout(5 * 1000);
		// 输入流
		InputStream is = con.getInputStream();
		// 2K的数据缓冲
		byte[] bs = new byte[2048];
		// 读取到的数据长度
		int len;
		// 输出的文件流
		File sf = new File( File.separator+"data"+File.separator+"jinzhiFile");
		if (!sf.exists()) {
			sf.mkdirs();
		}
		downloadFile = new File(sf.getPath() + File.separator + newfileName);
		System.out.println("downloadFile:" + sf.getPath() +File.separator + newfileName);

		OutputStream os = new FileOutputStream(sf.getPath() + File.separator+ newfileName);
		// 开始读取
		while ((len = is.read(bs)) != -1) {
			os.write(bs, 0, len);
		}
		// 完毕，关闭所有链接
		os.close();
		is.close();
		flag = true;


		if (flag) {
			//需要转换的文件为 downloadFile

			File convertFile = new File(newFileMix);//转换之后文件生成的地址
			//文件转化
			converter.convert(downloadFile).to(convertFile).execute();
			//转第二次，第一次pptx出现乱码。第二次不会
			converter.convert(downloadFile).to(convertFile).execute();
			PdfReader reader;

			reader = new PdfReader(newFileMix);
			pagecount = reader.getNumberOfPages();
			//关闭
			reader.close();




			System.out.println("-------------pagecount:" + pagecount);

			//删除下载的文件
			if (downloadFile.isFile() && downloadFile.exists()) {
				downloadFile.delete();
				System.out.println("删除单个文件" + downloadFile.getName() + "成功！");
			} else {
				System.out.println("删除单个文件" + downloadFile.getName() + "失败！");
			}


			FileInputStream fileInputStream = new FileInputStream(convertFile);
			MultipartFile multipartFile = new MockMultipartFile(convertFile.getName(), convertFile.getName(),
					ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

//			//上传到 minio服务器
//			String fileNames = DateUtils.format(new Date(), DateUtils.DATE_PATTERN_11) + "/" + multipartFile.getOriginalFilename();
//			Result result= minioUtil.minioUpload(multipartFile, fileNames, null);
//			uploadPdfUrl=result.getData().toString();
			uploadPdfUrl = ossService.uploadFileOss(multipartFile);
			System.out.println("uploadPdfUrl=" + uploadPdfUrl);
			mymap.put("status", "1");
			mymap.put("pdfUrl", uploadPdfUrl);
			//关闭
			fileInputStream.close();
			//删除转换的文件
			if (convertFile.isFile() && convertFile.exists()) {

				convertFile.delete();
				System.out.println("删除转换后的单个文件" + convertFile.getPath() + "成功！");
			} else {
				System.out.println("删除转换后的单个文件" + convertFile.getPath() + "失败！");
			}

		} else {
			System.out.println("下载文件失败！");
			mymap.put("status", "0");
			mymap.put("msg", "文件下载失败");
		}
		return mymap;
	}

	@RequestMapping(value = "/documentConversion", method = RequestMethod.POST)
	@ResponseBody
	public Result documentConversion(String resourceId) {

		DeclareFileDO chapterDocument = declareFileService.selectById(resourceId);
		Map map = new HashMap();
		//本身pdf
		//图片
		String[] imageTypes = {".jpg", ".jpeg", ".png", ".gif", ".bmp",".pdf"};
		boolean isImage=false;
		for (String type : imageTypes) {
			if (chapterDocument.getFile().toLowerCase().endsWith(type)) {
				isImage=true;
			}
		}
		if(isImage){
			map.put("pdfUrl", chapterDocument.getFile());
		}else {
			//获取数据看存不存在
			if (null==chapterDocument.getFilePdf()||chapterDocument.getFilePdf().trim().equals("")) {
				//转换保存
				Map oldmap = null;//转换文件为pdf文件
				try {
					oldmap = this.fileUrlToPdf(chapterDocument.getFile());
				} catch (Exception e) {
					System.out.println(e.getMessage());
				}
				if (null!=oldmap&&oldmap.get("status").toString().equals("1")) {
					//保存
					int number=declareFileService.updatePdfById(resourceId,oldmap.get("pdfUrl").toString());
					System.out.println("加入数据库"+number);
					map.put("pdfUrl", oldmap.get("pdfUrl").toString());
				}else{
					map.put("msg",null!=oldmap?oldmap.get("msg").toString():"异常");
				}
			}else{
				map.put("pdfUrl", chapterDocument.getFilePdf());
			}
		}
		Result r = new Result<>();
		r.setCode(200);
		r.setData(map);
		r.setMsg("获取成功！");
		return r;

	}
}
